package com.hopedove.workshop.viewmodel

import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.viewModelScope
import com.hadilq.liveevent.LiveEvent
import com.hopedove.data.Datetime
import com.hopedove.net.ApiCallResult
import com.hopedove.repository.CommonRepository
import com.hopedove.viewmodel.BaseViewModel
import com.hopedove.workshop.api.ExchangeBatchRemark
import com.hopedove.workshop.api.WorkshopApi
import com.hopedove.workshop.data.pojo.ExchangeBatchItem
import com.hopedove.workshop.repository.WorkshopUserRepository
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

class WorkshopExchangeBatchViewModel(
    private val commonRepo: CommonRepository,
    private val userRepo: WorkshopUserRepository,
    private val api: WorkshopApi
) : BaseViewModel() {

    val title = ObservableField("换批确认")
    val username = ObservableField("")
    val date = ObservableField(commonRepo.getServerDateTime().dateFormatCn())
    val batchNo = ObservableField("")
    val location = ObservableField("")
    val yarnName = ObservableField("")

    private val _pickDate = LiveEvent<Datetime>()
    val pickDate: LiveData<Datetime> = _pickDate

    private val _exchangeBatchList = MutableLiveData<List<ExchangeBatchItem>>(emptyList())
    val exchangeBatchList: LiveData<List<ExchangeBatchItem>> = _exchangeBatchList
    val noListData: LiveData<Boolean> =
        Transformations.map(exchangeBatchList) { it == null || it.isEmpty() }

    private val _remarks = MutableLiveData<List<ExchangeBatchRemark>>()
    val remarks: LiveData<List<String>> =
        Transformations.map(_remarks) { list -> list.map { it.SJXZ } }
    val selectedRemarkPosition = ObservableInt()

    private var confirmJob: Job? = null

    override fun load() = viewModelScope.launch {
        userRepo.getSignedInUserName()?.let { username.set("登录人：$it") }
        getRemarkList()
        queryExchangeBatchList()
    }

    private fun getRemarkList() = viewModelScope.launch {
        when (val result = api.exchangeBatchRemarkList()) {
            is ApiCallResult.Success -> {
                result.data?.let { data ->
                    val list = mutableListOf<ExchangeBatchRemark>().apply {
                        add(ExchangeBatchRemark("-1", "--请选择--"))
                        addAll(data)
                    }
                    _remarks.value = list
                }
            }
            is ApiCallResult.Error -> {
                // do nothing
            }
        }
    }

    private fun queryExchangeBatchList() = viewModelScope.launch {
        val loading = _loading.value ?: false

        val queryDate =
            date.get()?.let { Datetime.parseCnFormat(it).dateFormatEn() } ?: return@launch

        if (loading) return@launch

        _loading.value = true

        val remark = if (_remarks.value == null || selectedRemarkPosition.get() == 0) {
            ""
        } else {
            _remarks.value!![selectedRemarkPosition.get()].SJXZ
        }

        val userSession = userRepo.getSignedUserSession()!!

        val result = api.exchangeBatchList(
            userSession.userId,
            queryDate,
            location.get(),
            batchNo.get(),
            yarnName.get(),
            remark
        )

        when (result) {
            is ApiCallResult.Success -> {
                _exchangeBatchList.value = result.data!!.map {
                    ExchangeBatchItem(
                        it.PKID,
                        it.SZQC,
                        it.DIRECTION,
                        it.ORIPLACE,
                        it.BATCHNO,
                        it.ZBPD ?: "",
                        it.JGYQ ?: "",
                        it.REMARK ?: "",
                        it.N_ORIPLACE ?: "",
                        it.N_BATCHNO ?: "",
                        it.CLOTHNO ?: ""
                    )
                }
            }
            is ApiCallResult.Error -> {
                _toastText.value = result.message!!
            }
        }
    }.invokeOnCompletion { _loading.value = false }

    // 点击选择日期控件
    fun onPickDateClick() {
        val curDate = date.get() ?: commonRepo.getServerDateTime().dateFormatCn()
        _pickDate.value = Datetime.parseCnFormat(curDate)
    }

    // 更新日期
    fun updateDate(datetime: Datetime) {
        date.set(datetime.dateFormatCn())
    }


    // 点击确认
    fun onConfirmClick() {
        confirmList()
    }

    // 点击查询
    fun onQueryClick() {
        queryExchangeBatchList()
    }

    private fun confirmList() {
        if (exchangeBatchList.value?.isEmpty() == true) {
            _toastText.value = "列表为空"
            return
        }

        if (exchangeBatchList.value!!.none { it.op.get() }) {
            _toastText.value = "没有选中的条目"
            return
        }

        val userSession = userRepo.getSignedUserSession() ?: return

        if (confirmJob != null) return

        _loading.value = true
        confirmJob = viewModelScope.launch {
            val remaining = mutableListOf<ExchangeBatchItem>()
            val confirm = mutableListOf<ExchangeBatchItem>()
            exchangeBatchList.value!!.forEach { item ->
                if (item.op.get()) {
                    confirm.add(item)
                } else {
                    remaining.add(item)
                }
            }
            val ids = confirm.joinToString(separator = ",") { it.id }

            when (val result =
                api.exchangeBatchConfirm(userSession.userId, userSession.userName, ids)) {

                is ApiCallResult.Success -> {
                    _toastText.value = "确认成功"
                    // 刷新列表
                    _exchangeBatchList.value = remaining
                }

                is ApiCallResult.Error -> {
                    _toastText.value = result.error
                }

            }

        }.apply {
            invokeOnCompletion {
                confirmJob = null
                _loading.value = false
            }
        }


    }

}